//
// Created by 张兮兮 on 2025/3/11.
//

#include "SocketWidget.h"
#include <QPainterPath>
#include <QSysInfo>
#include <QDebug>
#include <QPushButton>
#include <QFile>
#include <QDir>
#include <QProcess>

QProcess *processSock;
bool openSocketProject = true;
QString imageSoPath = "/data/app/xth/socket-temp/temp/hand02.jpg";
//QString imageSoPath = "/Users/zhanghongwei/Desktop/temp/hand02.jpg";


SocketWidget::SocketWidget(QWidget *parent) : QWidget(parent) {
    socket = new QLocalSocket(this);
    connect(socket, &QLocalSocket::readyRead, this, &SocketWidget::readData);
    pid_t pid = getpid(); // 获取当前进程的进程ID
    if (openSocketProject) {
        pid = 23043;
    }
//    bool openProcess = !openSocketProject;
    QString processId = "socketHandPro" + QString::number(pid);
    qDebug() << "当前进程id" << processId;
    socketPath = QDir::temp().absoluteFilePath(processId);
    qDebug() << "System Info:" << QSysInfo::prettyProductName();
    image.load(imageSoPath);
    if (openSocketProject) {
        socket->connectToServer(socketPath);
        if (socket->waitForConnected(3000)) {
            isConnected = true;
            qDebug() << "Connected to server.";
            refresh();
        } else {
            qDebug() << "Unable to connect to server:" << socket->errorString();
        }
    } else {
        processSock = new QProcess(this);
        // 设置进程 B 的可执行文件路径
        QString program = "/Users/zhanghongwei/Desktop/socket-temp/socket-project/build/Debug/socketPro";
        // 设置参数
        QStringList arguments;
//        pid_t pid = getpid(); // 获取当前进程的进程ID
//        arguments << processId << QString::number(pid);
        arguments << processId;
        arguments << "/Users/zhanghongwei/Desktop/socket-temp/socket-project/res/track";
        // 启动进程 B 并传递参数
        processSock->start(program, arguments);
        // 等待进程 B 启动完成
        if (!processSock->waitForStarted()) {
            qDebug() << "Failed to start process B";
        }
        connect(processSock, &QProcess::readyReadStandardError, this, &SocketWidget::handleProcessOutput);
        connect(processSock, &QProcess::readyReadStandardOutput, this, &SocketWidget::handleProcessOutput);
    }

//    /Users/zhanghongwei/Downloads/素材/pingzi.mp4



    QPushButton *button = new QPushButton("点击刷新", this);
    button->setGeometry(10, 10, 100, 40); // 设置按钮位置和大小
    connect(button, &QPushButton::clicked, this, &SocketWidget::onButtonClicked);
}

void SocketWidget::onButtonClicked() {
    qDebug() << "按钮被点击！";
//    refresh(); // 调用 refresh() 发送图像
}

void SocketWidget::handleProcessOutput() {
    QByteArray outputError = processSock->readAllStandardError();
    QByteArray output = processSock->readAllStandardOutput();
    if (!outputError.isEmpty()) {
        qDebug() << "222222output:" << outputError;
    }
    if (!output.isEmpty()) {
        qDebug() << "1111111output:" << output;
    }
    if (outputError.contains("Server started successfully") || output.contains("Server started successfully")) {
        // 服务器已经启动，尝试连接
        socket->connectToServer(socketPath);
        if (socket->waitForConnected(3000)) {
            isConnected = true;
            qDebug() << "Connected to server.";
            refresh();
        } else {
            qDebug() << "Unable to connect to server:" << socket->errorString();
        }
    }
    qDebug() << "来爱仕达奋斗啥方式了";
}

void SocketWidget::readData() {
    QByteArray data = socket->readAll();
    QString response(data);
    qDebug() << "Received from B:" << response;
    qint64 elapsedTime = timer.elapsed();
    qDebug() << "hand_time----Output every five seconds--------:" << elapsedTime;
    refresh();
}


void SocketWidget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.drawImage(0, 0, image);
}


void SocketWidget::sendImage() {
    QByteArray imageData;
    QBuffer buffer(&imageData);
    if (!buffer.open(QIODevice::WriteOnly)) {
        qWarning() << "Failed to open buffer for writing";
        return;
    }
    if (openSocketProject) {
        QImage desImage = image.scaled(image.width() / 4.0, image.height() / 4.0);
        if (!desImage.save(&buffer, "BMP")) { // Save as BMP instead of JPG
            qWarning() << "Failed to save image to buffer";
            return;
        }
    } else {
        if (!image.save(&buffer, "JPG")) {
            qWarning() << "Failed to save image to buffer";
            return;
        }
    }
    buffer.close();
    qint64 imageSize = imageData.size();


    bool flag = true;


    qint64 bytesWritten = socket->write(reinterpret_cast<const char *>(&flag), sizeof(flag));
    qDebug() << "Writing flag:" << flag << "bytesWritten:" << bytesWritten;
    if (bytesWritten != sizeof(flag)) {
        qWarning() << "Failed to write flag to socket";
        return;
    }


    bytesWritten = socket->write(reinterpret_cast<const char *>(&imageSize), sizeof(imageSize));
    qDebug() << "Writing image size:" << imageSize << "bytesWritten:" << bytesWritten;
    if (bytesWritten != sizeof(imageSize)) {
        qWarning() << "Failed to write image size to socket";
        return;
    }
    if (!socket->waitForBytesWritten()) {
        qWarning() << "Error while waiting for image size data to be written";
        return;
    }
    bytesWritten = socket->write(imageData);
    if (bytesWritten != imageSize) {
        qWarning() << "Failed to write full image data to socket";
        return;
    }
    if (!socket->waitForBytesWritten()) {
        qWarning() << "Error while waiting for image data to be written";
    } else {
        imageData.clear();
    }
}

void SocketWidget::refresh() {
    if (isConnected) {
        if (socket->state() == QLocalSocket::ConnectedState) {
            timer.start();
            qDebug() << "send";
            sendImage();
        } else {
            if (socket->waitForConnected(2000)) {
                qDebug() << "22222Connected to server.";
                sendImage();
            } else {
                qDebug() << "1111Unable to connect to server:" << socket->errorString();
            }
        }
    }
}

SocketWidget::~SocketWidget() {
    disconnect(socket, &QLocalSocket::readyRead, this, &SocketWidget::readData);
    disconnect(processSock, &QProcess::readyReadStandardError, this, &SocketWidget::handleProcessOutput);
    disconnect(processSock, &QProcess::readyReadStandardOutput, this, &SocketWidget::handleProcessOutput);
    qDebug() << "析构";
    qDebug() << processSock->state();
    if (processSock && processSock->state() == QProcess::Running) {
        processSock->terminate();
        if (!processSock->waitForFinished(3000)) {
            qDebug() << "强杀";
            processSock->kill(); // 强制杀死进程
            qDebug() << processSock->state();
        }
    }
    qDebug() << processSock->state();
    qDebug() << socket->state();
    if (socket && socket->state() == QLocalSocket::ConnectedState) {
        socket->disconnectFromServer();
        qDebug() << "进来" << socket->state();
        if (socket && socket->state() == QLocalSocket::ConnectedState) {
            socket->waitForDisconnected(3000); //确保断开连接
        } else {
            qDebug() << "Socket is not connected, no need to wait for disconnection.";
        }
    }

    qDebug() << processSock->state();
    qDebug() << processSock->state();

    qDebug() << "析构结束";
}